package 树;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/invert-binary-tree/
 */
public class _226_翻转二叉树 {
     public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
   }

   //可以使用后序，前序遍历 实现
    //函数定义，传入一个节点，交换他的左右子节点
    public TreeNode invertTree(TreeNode root) {
       if(root == null) return null;

       TreeNode tmp = root.left;
       root.left = root.right;
       root.right = tmp;

       invertTree(root.left);
       invertTree(root.right);


       return root;
  }

    //利用层序遍历
    public TreeNode levelTree(TreeNode root){
        if(root == null) return root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
           TreeNode node = queue.poll();
           TreeNode tmp = node.left;
           node.left = node.right;
           node.right = tmp;

           if(node.left != null){
              queue.offer(node.left);
           }

           if(node.right != null){
              queue.offer(node.right);
           }
        }
        return root;
    }
}
